package com.zlq.cn.admin.controller;

import com.zlq.cn.ZlqApplication;
import com.zlq.cn.admin.domain.Menu;
import com.zlq.cn.admin.service.MenuService;
import com.zlq.cn.api.SignApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.PatternMatchUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "菜单")
@RestController
@RequestMapping("/api/menu")
public class MenuController {

    @Resource
    private MenuService menuService;

    @Resource
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @ApiOperation("接口列表")
    @PostMapping("/request_path_list")
    public SignApiResult<Collection<String>> apiPathList(String path) {
        String basePack = ZlqApplication.class.getPackage().getName();
        Collection<String> pathList = new TreeSet<>();
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
        handlerMethods.forEach((k, v) -> {
            Set<String> patterns = k.getPatternsCondition().getPatterns();
            patterns.forEach(pattern -> {
                if (v.getBeanType().getName().startsWith(basePack)) {
                    pathList.add(pattern);
                }
            });
        });
        if (!StringUtils.isEmpty(path)) {
            List<String> list = pathList.stream().filter(item -> item.contains(path) || PatternMatchUtils.simpleMatch(path, item)).collect(Collectors.toList());
            return SignApiResult.resultSuccess(list);
        }
        return SignApiResult.resultSuccess(pathList);
    }

    @ApiOperation("菜单列表")
    @PostMapping("/list")
    public SignApiResult<List<Menu>> list(String title, Integer type) {
        return SignApiResult.resultSuccess(menuService.getList(title, type));
    }

    @ApiOperation("菜单删除")
    @PostMapping("/delete")
    public SignApiResult<Boolean> delete(Integer id) {
        menuService.delete(id);
        return SignApiResult.resultSuccess(true);
    }

    @ApiOperation("菜单新增")
    @PostMapping("/save")
    public SignApiResult<Boolean> save(Menu menu) {
        menuService.save(menu);
        return SignApiResult.resultSuccess(true);
    }

}
